package reorderSpaces;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class Solution {
    public String reorderSpaces(String text) {
        // 统计出空格的数量
        // 统计出单词的数量
        int space = 0;
        int character = 0;
        List<String> words = new ArrayList<>();
        int i = 0,j = 0;
        while (i<text.length()&&j<text.length()) {
            if(text.charAt(i) == ' ')space++;
            if(!checkFirst(i,text)){
                i++;
            } else if (!checkLast(j,text)){
                j++;
            } else {
                words.add(text.substring(i,j+1));
                i++;
                j++;
            }
        }
        System.out.println(words);
        int t,e;
        if(words.size() == 1){
            t = 0;
            e = space;
        }else {
            t = space/(words.size()-1);
            e = space%(words.size()-1);
        }

        StringBuilder sb = new StringBuilder();
        for (int k = 0; k < words.size(); k++) {
            sb.append(words.get(k));
            if(k!=words.size()-1){
                // 拼接空格
                for (int l = 0; l < t; l++) {
                    sb.append(" ");
                }
            }
        }
        for (int k = 0; k < e; k++) {
            sb.append(" ");
        }
        return sb.toString();
    }
    private boolean checkFirst(int i,String s){
        if(i == 0) return s.charAt(i) != ' ';
        return s.charAt(i)!=' '&&s.charAt(i-1)==' ';
    }
    private boolean checkLast(int i,String s){
        if(i == s.length()-1) return s.charAt(i)!=' ';
        return s.charAt(i)!=' '&&s.charAt(i+1)==' ';
    }
    public int minOperations(String[] logs) {
        Stack<String> stack = new Stack<>();
        for (String s: logs) {
            if(s.equals("../")){
                if(!stack.isEmpty())stack.pop();
            } else if (s.equals("./")){
                continue;
            } else {
                stack.push(s);
            }
        }
        return stack.size();
    }
}
